package cn.itcast.datasource;

import cn.itcast.utils.JDBCUtil;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

public class MyDataSource implements DataSource {
    //定义存储连接的容器
    private static List<Connection> pool = Collections.synchronizedList(new ArrayList<Connection>());

    //静态代码块中向容器里存储十个连接
    static {
        for (int i = 1; i <= 10; i++) {
            Connection conn = JDBCUtil.getConn();
            pool.add(conn);
        }
    }

    //定义一个方法,获取连接池中的连接数量
    public int getSize() {
        return pool.size();
    }


    public Connection getConnection() throws SQLException {
        if (pool.size() > 0) {//容器里如果还有连接返回连接
            Connection conn = pool.remove(0);

         return (Connection) Proxy.newProxyInstance(conn.getClass().getClassLoader(), new Class[]{Connection.class}, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    //增强close方法
                    if ("close".equals(method.getName())) {
                        pool.add(conn);
                        return null;
                    } else {//不是close方法,执行原有方法
                        return method.invoke(conn, args);
                    }
                }
            });


        } else {
            throw new RuntimeException("连接已用尽");
        }


    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
